package com.boe.hbd.client.activity;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.boe.hbd.client.Constants;
import com.boe.hbd.client.R;
import com.boe.hbd.client.collections.CollectionsAdapter;
import com.boe.hbd.client.contextmenu.IconContextMenu.IconContextItemSelectedListener;
import com.boe.hbd.client.domain.Landscape;
import com.boe.hbd.client.persistence.EntityManager;
import com.boe.hbd.client.service.LandscapeService;
import com.boe.hbd.client.service.LocationService;
import com.boe.hbd.client.service.ServiceManager;
import com.boe.hbd.client.utils.GpsPoint;
import com.boe.hbd.client.utils.Utils;

public class LandscapeListActivity  extends ListActivity implements SimpleAdapter.ViewBinder,IconContextItemSelectedListener, TextWatcher, OnItemSelectedListener { 
    private LandscapeService landscapeService= null ; 
    private LocationService locationService  = null ;
    private EntityManager entityManager      = null ;
    private SimpleAdapter mAdapter           = null ;
    private SimpleDateFormat dateFormat      = null ;
    private TextView mFilter                 = null ;  
    private List<Landscape> landscapes       = null ;
    private Spinner distanceSpinner;
    
	public void onCreate(Bundle theInstance) {
		// STEP 1: initialize the UI
		super.onCreate(theInstance);
		setContentView(R.layout.landscape_list_activity);     
		// STEP 2: initialize the service instances 
		landscapeService = ServiceManager.getInstance(null).getService(LandscapeService.class); 
		locationService  = ServiceManager.getInstance(null).getService(LocationService.class);
		entityManager    = ServiceManager.getInstance(null).getService(EntityManager.class);
		dateFormat       = new SimpleDateFormat(getResources().getString(R.string.date_format));
		 
        distanceSpinner =  ((Spinner)findViewById(R.id.distanceSpinner)) ;
		CollectionsAdapter<String> spinnerAdapter = new CollectionsAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, Arrays.asList(getResources().getStringArray(R.array.distance_labels)));
        distanceSpinner.setAdapter(spinnerAdapter);
        
        distanceSpinner.setOnItemSelectedListener(this);
        
		// STEP 3: build the list adapter
		getListView().setItemsCanFocus(true);
		registerForContextMenu(getListView());
		// STEP 4:  initialize the filter search box
        mFilter = (TextView) findViewById(R.id.searchFilter);
        if (mFilter != null) {
            mFilter.addTextChangedListener(this);
        } 
        // STEP 6: retrieve data from back end
        refreshListView();
	}
 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			refreshListView();
		}
	}
	
	public boolean setViewValue(View view, final Object data, String text) {
		if (view.getId() == R.id.row_gmt_created) {
			String gmtCreated = dateFormat.format(new Date((Long) data));
			((TextView) view).setText(gmtCreated);
			return true;
		} else if (view.getId() == R.id.row_created_by) {
			String createdBy = getResources().getString(R.string.created_by_unknown);
			if (data != null && !data.equals("")) {
				createdBy = data.toString();
			}
			((TextView) view).setText(createdBy);
			return true;
		} else if (view.getId() == R.id.row_options_button) {
			view.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					LandscapeHelper.buildContextMenu(LandscapeListActivity.this, LandscapeListActivity.this, data, R.menu.main_view_existing_landscape );
				}
			});
			return true;
		}
		return false;
	}

	public void onIconContextItemSelected(MenuItem item, Object data) {
		if (data != null) {
			Long landscapeId = (Long)data;
			Landscape landscape = entityManager.getById(Landscape.class, landscapeId);
			if (landscape != null ) {
				if (item.getItemId() == R.id.deleteLandscape ) {
					entityManager.remove(landscape);
					refreshListView();
				} else {
					int cmdId = item.getItemId();
					LandscapeHelper.processRequestForLandscape(this,landscapeId, cmdId);
				}
			}
		}
	}
	
	protected void refreshListView() {
		Location here = null;
		if (getIntent().getExtras().getDouble(Constants.KEY_LATITUDE) != 0.0D ) {
			here = new Location("GPS");
			here.setLatitude(getIntent().getExtras().getDouble(Constants.KEY_LATITUDE));
			here.setLongitude(getIntent().getExtras().getDouble(Constants.KEY_LONGTITUDE));
		}
		if (here == null) {
			here = locationService.getLocation();
		}
		int pos = distanceSpinner.getSelectedItemPosition();
		int distnace = getResources().getIntArray(R.array.distance_values)[pos];
		if ( here != null ) {
			double distance = Math.sqrt(distnace*distnace*2);
			GpsPoint topLeft     = Utils.relativeGpsPoint(here.getLatitude(), here.getLongitude(), 315 , distance);
			GpsPoint bottomRight = Utils.relativeGpsPoint(here.getLatitude(), here.getLongitude(), 135 , distance);
			
			landscapes = landscapeService.findLandscapesByArea(topLeft, bottomRight, new GpsPoint(here),mFilter.getText().toString() , null , null);
			mAdapter = new SimpleAdapter(
				  this
			    , landscapes
			    , R.layout.landscape_list_item
			    , new String[]{ "gmtCreated" , "createdBy" , "name" , "id" }
				, new int[]{R.id.row_gmt_created,R.id.row_created_by,R.id.row_title,R.id.row_options_button});
			mAdapter.setViewBinder(this);
			setListAdapter(mAdapter); 
		}
	}

	public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) { 
	}

	public void afterTextChanged(Editable s) {
		refreshListView();
	}

	public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
		refreshListView();
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}
}
